# -*- coding: utf-8 -*-
from django.template.loader import get_template
from django import template
import datetime
import decimal
import json

register = template.Library()

@register.filter
def as_table_form(form_or_field):
    """
    格式化表单table样式
    """
    return get_template("table_form.html").render({'form': form_or_field})

@register.filter
def data2json(object_list):
    """
    object转json
    """
    object_dict = object_list.__dict__
    new_dict = {}
    for key,val in object_dict.items():
        if not key.startswith('_'):
            if isinstance(val, datetime.datetime):
                val = val.strftime('%Y-%m-%d %H:%M:%S')
            elif isinstance(val, decimal.Decimal):
                val = str(val)
            new_dict[key] = val
    return json.dumps(new_dict)

@register.filter(name='set_br')
def set_br(value):
    return value.replace(',','<br>').replace(u'，','<br>')

@register.filter(name='format_url')
def format_url(url):
    if not url.startswith('http://'):
        url = 'http://'+url
    if url.endswith('/'):
        url = url[:-1]
    return url
